package common.guide
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.InteractiveObject;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import kernel.application.ApplicationDisplay;

	public class GuideForce
	{
		private static var _instance:GuideForce;
		private static const ORIGIN:Point = new Point();
		private var _view:Sprite;
		private var _ishit:Boolean
		
		public function GuideForce()
		{
			_view = new Sprite();
		}
		public static function get instance():GuideForce
		{
			if(_instance == null)
			{
				_instance = new GuideForce();
			}
			return _instance;
		}
		/**
		 * 显示
		 * @param name
		 * 
		 */		
		public function show(owner:InteractiveObject,assets:DisplayObjectContainer,ishit:Boolean=false,offsetX:int=0, offsetY:int=0):void
		{
			close();
			
			var p:Point = owner.localToGlobal(ORIGIN);
			assets.x = p.x + offsetX;
			assets.y = p.y + offsetY;
			
			drow(assets);
			
			_ishit = ishit;
			if(_ishit)
			{
				_view.addEventListener(MouseEvent.CLICK,onHit);
			}
			
			if(_view.parent==null)
			{
				ApplicationDisplay.stage.addChild(_view);
			}
		}
		/**
		 *关闭 
		 * 
		 */		
		public function close():void
		{
			if(_view.parent!=null)
			{
				_view.parent.removeChild(_view);
			}
			if(_ishit)
			{
				_view.removeEventListener(MouseEvent.CLICK,onHit);
			}
			var len:uint=_view.numChildren;
			for(var i:uint=0;i<len;i++)
			{
				_view.removeChildAt(len-1-i);
			}
		}
		/**
		 * 取消 
		 * @param evt
		 * 
		 */		
		private function onHit(evt:MouseEvent):void
		{
			close();
		}
		/**
		 * 绘制背景 
		 * @param dis
		 * 
		 */		
		private function drow(assets:DisplayObjectContainer):void
		{
			var dis:DisplayObject = assets.getChildByName("mc") as DisplayObject;
			if(dis==null)
			{
				_view.addChild(drowShape( 0, 0,ApplicationDisplay.stage.stageWidth , ApplicationDisplay.stage.stageHeight ));
			}else{
				
				var p:Point = dis.localToGlobal(ORIGIN);
				_view.addChild(drowShape( 0, 0,ApplicationDisplay.stage.stageWidth , p.y ));
				_view.addChild(drowShape( 0, p.y+dis.height,ApplicationDisplay.stage.stageWidth , ApplicationDisplay.stage.stageHeight- p.y+dis.height));
				_view.addChild(drowShape( 0, p.y,p.x, dis.height));
				_view.addChild(drowShape( p.x+dis.width, p.y,p.x, dis.height));
				
				assets.removeChild(dis);
			}
			_view.addChild(assets);
			
		}
		private function drowShape(dx:int,dy:int,dw:int,dh:int):Shape
		{
			var bg:Shape = new Shape();
			bg = new Shape();
			bg.graphics.clear();
			bg.graphics.beginFill( 0,0x999999);
			bg.graphics.drawRect( dx,dy,dw , dh);
			bg.graphics.endFill();
			bg.alpha=0.5;
			
			return bg;
		}
	}
}